package com.stylefeng.guns.modular.product.controller;

import com.stylefeng.guns.config.properties.GunsProperties;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.support.DateTime;
import com.stylefeng.guns.modular.product.service.IDataImportService;
import com.stylefeng.guns.modular.product.service.IExcelUploadService;
import com.stylefeng.guns.modular.product.model.ExcelUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
@RequestMapping("/dataImport")
public class DataImportController extends BaseController {

    private String PREFIX = "/product/dataImport/";

    @Autowired
    private GunsProperties gunsProperties;

    @Autowired
    private IExcelUploadService excelUploadService;

    @Autowired
    private IDataImportService dataImportService;

    /**
     * 跳转到数据导入首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "dataImport.html";
    }


    /**
     * 获取数据导入列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(String condition) {
        return excelUploadService.selectList(null);
    }


    /**
     * 上传excel
     */
    @RequestMapping(method = RequestMethod.POST, path = "/uploadProduct")
    @Permission(Const.ADMIN_NAME)
    @ResponseBody
    public String uploadProduct(@RequestPart("file") MultipartFile excelFile) {
        String originalFilename = excelFile.getOriginalFilename();
        String fileSavePath = gunsProperties.getExcelUploadPath();
        try{
            //int a = 1/0;
            excelFile.transferTo(new File(fileSavePath + originalFilename));
            //excelImport(excelFile);
            boolean result = dataImportService.parseExcelFileToData(excelFile);
            if(result){
                ExcelUpload excelUpload = new ExcelUpload();
                excelUpload.setFilename(originalFilename);
                excelUpload.setUploadtime(new DateTime());
                excelUploadService.insert(excelUpload);
            }
        }catch (Exception e){
            throw new GunsException(BizExceptionEnum.FILE_READING_ERROR);
        }
        return originalFilename;
    }
}
